package example.cdx.com.camerademo;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.TextureView;
import android.view.WindowManager;
import android.widget.FrameLayout;

public class Test1Activity extends AppCompatActivity {

    private static final String TAG = Test1Activity.class.getSimpleName();

    private Camera mCamera;//照相机
    private FrameLayout mFlContainer;//容器
    private TextureView mTextureView;//显示View
    private static final long INTERVEL_AUTOFOCUS = 2000L;

    private Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            //第六步：设置缓存
            //在onPreviewFrame调用addCallbackBuffer(data)即可，就可以一直复用原来开辟的那个内存空间
            //数据会永远的保存在一个地址中，只是其中的内容在不断的变化。
            camera.addCallbackBuffer(data);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        setContentView(R.layout.activity_test1);

        initView();
    }

    private void initView() {
        mFlContainer = findViewById(R.id.fl_container);
        mTextureView = findViewById(R.id.textureView);
        //第一步：设置TextureView的监听
        Log.e(TAG, "开始监听");
        mTextureView.setSurfaceTextureListener(mListener);
    }

    TextureView.SurfaceTextureListener mListener = new TextureView.SurfaceTextureListener() {
        //SurfaceTexture可用的时候调用
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //第二步：初始化Camera
            initCamera(surface);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {

            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    };

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private void initCamera(SurfaceTexture surface) {
        //第三步：通过Camera.open方法获得Camera的对象
        getCameraInstance();
        //第四步：设置照相机的参数（用于展示预览的图像，还有大小等参数），并且将结果返回
        boolean result = setCameraParam(surface);
        //第五步：开始预览，Camera将图像传递到SurfaceTexture，进而传递到TextureView
        if (result) {
            mCamera.startPreview();
        }

        //第七步：2秒以后自动对焦
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(mAutoFocusTask, INTERVEL_AUTOFOCUS);
    }

    /**
     * 给Camera设置参数
     *
     * @param surface
     * @return
     */
    private boolean setCameraParam(SurfaceTexture surface) {
        Log.e(TAG, "设置Camera的参数");
        try {
            if (mCamera != null) {
                //将相机获取到的一帧放到surfaceTexture上
                mCamera.setPreviewTexture(surface);
                //重新设置预览的图的大小
                Camera.Parameters parameters = mCamera.getParameters();
                parameters.setPreviewSize(1920, 1080);
                mCamera.setParameters(parameters);
                //由于摄像头获取到的画面是横向来展示的，但是你的应用时竖直来展示的，解决办法是
                //调用setDisplayOrientation来设置PreviewDisplay的方向
                mCamera.setDisplayOrientation(90);
                //预览之前设置缓存，可以一直复用内存空间，数据会一直存储在内存空间中
                byte[] mPreviewBuffer = new byte[1440 * 1080 * 2];
                mCamera.addCallbackBuffer(mPreviewBuffer);
                //设置预览的回调
                mCamera.setPreviewCallbackWithBuffer(mPreviewCallback);
                return true;
            } else {
                return false;
            }
        } catch (Throwable throwable) {
            return false;
        }
    }

    private void getCameraInstance() {
        Log.e(TAG, "获得Camera的实例");
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
        }
    }

    private Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            Log.e(TAG, "执行聚焦任务");
            mHandler.postDelayed(mAutoFocusTask, INTERVEL_AUTOFOCUS);
        }
    };

    private Runnable mAutoFocusTask = new Runnable() {
        @Override
        public void run() {
            Log.e(TAG, "执行任务");
            try {
                mCamera.autoFocus(mAutoFocusCallback);
            } catch (Throwable throwable) {
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除mHandler
        mHandler.removeCallbacksAndMessages(null);

        if (mCamera != null){
            //清除缓存
            mCamera.setPreviewCallbackWithBuffer(null);
            //停止预览
            mCamera.stopPreview();
            //释放，下一次进入open的时候才能获得Camera对象
            mCamera.release();
        }

        //释放预览的图片
        SurfaceTexture st = mTextureView.getSurfaceTexture();
        if (st != null) {
            st.release();
        }
    }
}
